<?php
/**
 * 测试二级分类API
 */

require_once __DIR__ . '/backend/support/bootstrap.php';

use app\model\GoodsCatModel;

/**
 * 测试二级分类API
 */
function testSubCategoriesApi() {
    echo "=== 测试二级分类API ===\n";
    
    try {
        // 获取所有一级分类
        $mainCategories = GoodsCatModel::where('status', 1)
            ->where('fid', 0)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'asc')
            ->get();
        
        echo "一级分类列表:\n";
        foreach ($mainCategories as $category) {
            echo "- ID: {$category->id}, 名称: {$category->name}\n";
            
            // 获取该分类的二级分类
            $subCategories = GoodsCatModel::where('status', 1)
                ->where('fid', $category->id)
                ->orderBy('sort', 'asc')
                ->orderBy('id', 'asc')
                ->get();
            
            if ($subCategories->count() > 0) {
                echo "  二级分类:\n";
                foreach ($subCategories as $subCat) {
                    echo "    - ID: {$subCat->id}, 名称: {$subCat->name}\n";
                }
            } else {
                echo "  无二级分类\n";
            }
            echo "\n";
        }
        
        // 模拟API响应格式
        if ($mainCategories->count() > 0) {
            $firstCategory = $mainCategories->first();
            $subCategories = GoodsCatModel::where('status', 1)
                ->where('fid', $firstCategory->id)
                ->orderBy('sort', 'asc')
                ->orderBy('id', 'asc')
                ->get();
            
            $subCatList = [];
            foreach ($subCategories as $subCat) {
                $subCatList[] = [
                    'id' => $subCat->id,
                    'text' => $subCat->name,
                ];
            }
            
            echo "API响应格式 (cat_id = {$firstCategory->id}):\n";
            echo json_encode([
                'code' => 1,
                'msg' => '获取二级分类成功',
                'data' => $subCatList
            ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
            echo "\n";
        }
        
    } catch (Exception $e) {
        echo "测试失败: " . $e->getMessage() . "\n";
    }
}

// 执行测试
echo "开始二级分类API测试\n";
echo "==================\n\n";

testSubCategoriesApi();

echo "测试完成！\n";
echo "==================\n";
echo "API说明：\n";
echo "1. 路径: /v1/goods/sub-categories\n";
echo "2. 参数: cat_id (一级分类ID)\n";
echo "3. 返回: 该分类下的所有二级分类列表\n"; 